//
//  MSInviteVC.m
//  MSMain
//
//  Created by Dgh Hv on 2018/9/18.
//  Copyright © 2018年 土豆. All rights reserved.
//

#import "MSInviteVC.h"
#import "MSShareView.h"
#import "MSInviteViewModel.h"
#import "WeChatShareHandler.h"
#import "MSQRCodeView.h"
#import "MSAwardAndInviteVC.h"

@interface MSInviteVC ()
@property (weak, nonatomic) IBOutlet UIButton *inviteButton;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIScrollView *backScrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeight;
@property (weak, nonatomic) IBOutlet UIView *contentBackView;
//最底部的label的约束距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;
- (IBAction)didClickInviteButton:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *rewardLabel;
@property (weak, nonatomic) IBOutlet UILabel *invitePeopleNum;

@property (nonatomic, strong)MSShareView * shareView;
@property (nonatomic, strong)MSQRCodeView * QRCodeView;
@property (nonatomic, strong)MSInviteViewModel * viewModel;
@property (nonatomic, copy)NSString * shareUrl;  //分享url
@property (nonatomic, copy)NSString * shareTitle; //分享标题
@property (nonatomic, copy)NSString * shareContent; //分享内容

@end

@implementation MSInviteVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self getData];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.backScrollView.contentSize = CGSizeMake(KScreenWidth, 603);
}

#pragma mark - get  data
-(void)getData
{
    kWeakSelf(self);
    [self.viewModel getAnchorInviteInfoComplete:^(NSString *Reward, NSString *SubordinateCount) {
        [MBProgressHUD hideHUDForView:weakself.view];
        weakself.rewardLabel.text = Reward;
        weakself.invitePeopleNum.text = SubordinateCount;
    }];
    
    [self.viewModel getAnchorInviteContentComplete:^(NSString *Content, NSString *InviteUrl, NSString *Title) {
        weakself.shareUrl = InviteUrl;
        weakself.shareTitle = Title;
        weakself.shareContent = Content;
    }];
}


#pragma mark - set  UI
-(void)setUI
{
    self.title = @"邀请好友";
    ViewBorderRadius(self.contentView, 0, 0.5, RGB_HEX(0xE4A806));
    ViewRadius(self.inviteButton, 5);
    if(KScreenHeight >= 667)
    {
        self.backViewHeight.constant = KScreenHeight - kTopHeight;
    }else{
        self.backViewHeight.constant = 603;
    }
    
    [self addNavigationItemWithTitles:@[@"奖励详情"] isLeft:NO target:self action:@selector(didClickRightButton) tags:nil btnColors:nil];
    
    // 阴影颜色
    self.contentView.layer.shadowColor = KBlackColor.CGColor;
    // 阴影偏移，默认(0, -3)
    self.contentView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    self.contentView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    self.contentView.layer.shadowRadius = 5;
    self.bottomHeight.constant = kViewToBottom + 7;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - click event
- (IBAction)didClickInviteButton:(id)sender {
    if(ValidStr(self.shareUrl))
    {
        //主播推广地址获取成功
        self.shareView.hidden = NO;
    }else
    {
        kWeakSelf(self);
        [self.viewModel getAnchorInviteContentComplete:^(NSString *Content, NSString *InviteUrl, NSString *Title) {
            weakself.shareUrl = InviteUrl;
            weakself.shareTitle = Title;
            weakself.shareContent = Content;
            weakself.shareView.hidden = NO;
        }];
    }
}

-(void)didClickRightButton
{
    MSAwardAndInviteVC * vc = [[MSAwardAndInviteVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - getters & setters
-(MSShareView *)shareView
{
    if(_shareView == nil)
    {
        _shareView = [[MSShareView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        kWeakSelf(self);
        _shareView.block = ^(ShareType type) {
            //主播推广地址获取成功
            [weakself shareWithType:type];  
        };
        _shareView.hidden = YES;
        [kAppWindow addSubview:_shareView];
    }
    return _shareView;
}


-(void)shareWithType:(ShareType)type
{
    switch (type) {
        case ShareTypeWeChat:
        {
            [WeChatShareHandler sendLinkURL:self.shareUrl TagName:@"" Title:self.shareTitle Description:self.shareContent ThumbImage:IMAGE_NAMED(@"AppIcon") InScene:WXSceneSession];
        }
            break;
        case ShareTypeFriend:
        {
            [WeChatShareHandler sendLinkURL:self.shareUrl TagName:@"" Title:self.shareTitle Description:self.shareContent ThumbImage:IMAGE_NAMED(@"AppIcon") InScene:WXSceneTimeline];
        }
            break;
        case ShareTypeQRCode:
        {
            //创建过滤器
            CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
            //过滤器恢复默认
            [filter setDefaults];
            //将NSString格式转化成NSData格式
            NSData *data = [self.shareUrl dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            [filter setValue:data forKeyPath:@"inputMessage"];
            //获取二维码过滤器生成的二维码
            CIImage *image = [filter outputImage];
            //将获取到的二维码添加到imageview上
            if(self.QRCodeView == nil)
            {
                self.QRCodeView = [[MSQRCodeView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) AndQRImage:[self createNonInterpolatedUIImageFormCIImage:image withSize:100]];
                [kAppWindow addSubview:self.QRCodeView];
            }else
            {
                self.QRCodeView.hidden = NO;
            }
            
        }
            break;
            
        default:
            break;
    }
}


/**
*  根据CIImage生成指定大小的UIImage
*
*  @param image CIImage
  *  @param size  图片宽度
*/
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
     CGRect extent = CGRectIntegral(image.extent);
     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
     // 1.创建bitmap;
     size_t width = CGRectGetWidth(extent) * scale;
     size_t height = CGRectGetHeight(extent) * scale;
     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
     CIContext *context = [CIContext contextWithOptions:nil];
     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
     CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
     CGContextScaleCTM(bitmapRef, scale, scale);
     CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
     CGContextRelease(bitmapRef);
     CGImageRelease(bitmapImage);
     return [UIImage imageWithCGImage:scaledImage];
    
}


-(MSInviteViewModel *)viewModel
{
    if(_viewModel == nil)
    {
        _viewModel = [[MSInviteViewModel alloc]init];
    }
    return _viewModel;
}

@end
